﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Security.Principal;
using System.ServiceProcess;
using System.Xml;
using Microsoft.Win32;


namespace WUTOS.DataBase.DataBaseDAL
{
    public class BLL
    {
        #region -服务器版本及登陆模式-
        public struct databaseversion
        {
            public string version;
            public int loginmode;
        }
        #endregion

        /// <summary>
        /// 重启服务器
        /// </summary>
        /// <param name="sqlServerClass">服务器类型:true(MSSQLSERVER),false(SQLEXPRESS）</param>
        public static bool RestartSqlserver(bool sqlServerClass)
        {
            Process process = new Process();
            if (sqlServerClass)
            {
                process.StartInfo = new ProcessStartInfo("cmd.exe", @"  /C  net  stop  mssqlserver &&  net  start mssqlserver");
                process.StartInfo.CreateNoWindow = true;
                process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            }
            else
            {
                process.StartInfo = new ProcessStartInfo("cmd.exe", @"  /C  net  stop  mssql$sqlexpress  &&  net start  mssql$sqlexpress");
                process.StartInfo.CreateNoWindow = true;
                process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            }

            if (process.Start())
            {
                ProcessFrame dlg = new ProcessFrame();
                dlg.Psid = process.Id;
                dlg.ShowDialog();
            }
            return true;
        }

        /// <summary>
        /// 判断服务是否启动
        /// </summary>
        /// <param name="ExistFlag_Express">Express：true，SQLEXPRESS未启动</param>
        /// <param name="ExistFlag_MSSQL">MSSQL：true，MSSQL未启动</param>
        public static void IsSqlserverExit(ref bool ExistFlag_Express, ref bool ExistFlag_MSSQL)
        {
            ExistFlag_Express = true;
            ExistFlag_MSSQL = true;
            ServiceController[] service = ServiceController.GetServices();
            for (int i = 0; i < service.Length; i++)
            {
                if (ExistFlag_Express)
                {
                    ExistFlag_Express = (service[i].DisplayName.ToString()).Contains("SQLEXPRESS") ? false : true;

                }
                if (ExistFlag_MSSQL)
                {
                    ExistFlag_MSSQL = (service[i].DisplayName.ToString()).Contains("MSSQLSERVER") ? false : true;
                }
            }
        }

        /// <summary>
        /// 获取本地数据库版本
        /// </summary>
        public static List<databaseversion> GetLocalDataBaseVersion()
        {
            List<databaseversion> localDBbVersion = new List<databaseversion>();

            RegistryKey hlmk = Registry.LocalMachine;
            //2005或2008版本的判断
            RegistryKey key = hlmk.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server", true);
            //2000版本的判断
            RegistryKey key_2000 = hlmk.OpenSubKey(@"SOFTWARE\Microsoft\MSSQLServer\Setup", true);
            if (key != null)
            {
                string[] keynames = key.GetSubKeyNames();
                foreach (string mssql in keynames)
                {
                    databaseversion dataversion;
                    if (mssql.Contains("MSSQL"))
                    {
                        key = hlmk.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\" + mssql + @"\Setup", true);
                        if (key != null)
                        {
                            string keyvalue = (string)key.GetValue("FeatureList");
                            if (keyvalue != null && keyvalue.Contains("SQL_Engine"))
                            {
                                string versionvalue = (string)key.GetValue("Version");
                                if (versionvalue != null)
                                {
                                    //只适合于2005和2008SQL：develpoer和express版本数据库
                                    if (versionvalue.StartsWith("9."))
                                    {
                                        dataversion.version = "SQL Server 2005 ";
                                    }
                                    else //(versionvalue.StartsWith("10."))
                                    {
                                        dataversion.version = "SQL Server 2008 ";
                                    }
                                    string editValue = (string)key.GetValue("Edition");
                                    if (editValue != null)
                                    {
                                        dataversion.version += editValue;

                                    }
                                    key = hlmk.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\" + mssql + @"\MSSQLServer", true);
                                    dataversion.loginmode = (int)key.GetValue("LoginMode");
                                    localDBbVersion.Add(dataversion);
                                }
                            }
                        }
                    }
                }
            }
            if (key_2000 != null)
            {
                databaseversion dataversion;
                string keyname = (string)key_2000.GetValue("Edition");
                if (keyname != null)
                {
                    dataversion.version = "SQL Server 2000" + keyname;
                    key_2000 = hlmk.OpenSubKey(@"SOFTWARE\Microsoft\MSSQLServer\MSSQLServer", true);
                    dataversion.loginmode = (int)key_2000.GetValue("LoginMode");
                    localDBbVersion.Add(dataversion);
                }
            }
            return localDBbVersion;

        }

        /// <summary>
        /// 通过名称查找数据库版本
        /// </summary>
        /// <param name="dvName"></param>
        /// <returns></returns>
        public static string SearchStringLocalDbList(string dvName)
        {
            List<databaseversion> dvList = GetLocalDataBaseVersion();
            foreach (BLL.databaseversion Version in dvList)
            {
                if (Version.version == dvName)
                {
                    return Version.version;
                }
            }
            return null;
        }

        /// <summary>
        /// 通过名称查找数据库版本列表
        /// </summary>
        /// <param name="dvName"></param>
        /// <returns></returns>
        public static databaseversion SearchLocalDbList(string dvName)
        {
            List<databaseversion> dvList = GetLocalDataBaseVersion();
            foreach (BLL.databaseversion Version in dvList)
            {
                if (Version.version == dvName)
                {
                    return Version;
                }
            }
            return new databaseversion();
        }

        /// <summary>
        /// 读取XML配置
        /// </summary>
        /// <returns></returns>
        public static BLL.databaseversion ReadConfigXml()
        {
            try
            {
                databaseversion dv = new databaseversion();
                if (File.Exists("DataConfig.xml"))
                {
                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.Load("DataConfig.xml");
                    XmlNode nodeVersion = xmlDoc.SelectSingleNode("DataVersion");
                    if (nodeVersion.HasChildNodes)
                    {
                        foreach (XmlNode node in nodeVersion.ChildNodes)
                        {
                            switch (node.Name)
                            {
                                case "Version":
                                    dv.version = node.InnerText;
                                    break;
                                case "LoginMode":
                                    dv.loginmode = Convert.ToInt32(node.InnerText);
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                    return dv;
                }
                else
                {
                    CreateConfigXml();
                    return dv;
                }
            }
            catch (Exception)
            {
                throw;
            }
            return new databaseversion();
        }

        /// <summary>
        /// 创建XML文件
        /// </summary>
        private static void CreateConfigXml()
        {
            try
            {
                XmlDocument xmlDoc = new XmlDocument();
                XmlNode dbversionNode = xmlDoc.CreateNode(XmlNodeType.Element, "DataVersion", null);
                XmlNode versionNode = xmlDoc.CreateNode(XmlNodeType.Element, "Version", null);
                XmlNode loginModelNode = xmlDoc.CreateNode(XmlNodeType.Element, "LoginMode", null);
                dbversionNode.AppendChild(versionNode);
                dbversionNode.AppendChild(loginModelNode);
                xmlDoc.AppendChild(dbversionNode);
                xmlDoc.Save(Path.Combine(Directory.GetCurrentDirectory(), "DataConfig.xml"));
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        /// <summary>
        /// 存储数据库配置信息
        /// </summary>
        /// <param name="version"></param>
        public static void SaveConfigToXml(databaseversion version)
        {
            try
            {
                if (File.Exists("DataConfig.xml"))
                {
                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.Load("DataConfig.xml");
                    XmlNode nodeVersion = xmlDoc.SelectSingleNode("DataVersion");
                    if (nodeVersion.HasChildNodes)
                    {
                        nodeVersion.RemoveAll();
                    }
                    XmlElement xmlVersion = xmlDoc.CreateElement("Version", null);
                    XmlElement xmlLoginMode = xmlDoc.CreateElement("LoginMode", null);
                    xmlVersion.InnerText = version.version.ToString();
                    xmlLoginMode.InnerText = version.loginmode.ToString();
                    nodeVersion.AppendChild(xmlVersion);
                    nodeVersion.AppendChild(xmlLoginMode);
                    xmlDoc.Save("DataConfig.xml");
                }
                else
                {
                    return;
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 改变访问模式
        /// </summary>
        /// <param name="DBversion"></param>
        /// <param name="loginmode"></param>
        public static void ChangeLoginMode(string DBversion, int loginmode)
        {
            RegistryKey hlmk = Registry.LocalMachine;
            RegistryKey key;
            if (DBversion.Contains("2000"))
            {
                key = hlmk.OpenSubKey(@"SOFTWARE\Microsoft\MSSQLServer\MSSQLServer", true);
                key.SetValue("LoginMode", loginmode);
            }
            else
            {
                //判断数据库版本
                string version = DBversion.Contains("2005") ? "9." : "10.";
                key = hlmk.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server", true);
                string[] keynames = key.GetSubKeyNames();
                foreach (string keyname in keynames)
                {
                    if (keyname.Contains("MSSQL"))
                    {
                        key = hlmk.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\" + keyname + @"\Setup", true);
                        if (key != null)
                        {
                            string versionvalue = (string)key.GetValue("Version");
                            string sqlengine = (string)key.GetValue("FeatureList");
                            if (sqlengine.Contains("SQL_Engine") && versionvalue.Contains(version))
                            {
                                key = hlmk.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\" + keyname + @"\MSSQLServer", true);
                                if (key != null)
                                {
                                    key.SetValue("LoginMode", loginmode);
                                }
                            }
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 连接测试
        /// </summary>
        /// <param name="loginMdel">登陆模式</param>
        /// <param name="databaseModel">数据库实体</param>
        /// <param name="errormsg">错误提示</param>
        /// <returns>true:成功</returns>
        public static bool ConnectionTest(int loginMdel, DataBaseInfo databaseModel, ref string errormsg)
        {
            string sqlconnnect = DataBaseDAL.DAL.SetConnectionString(loginMdel, databaseModel);
            return DataBaseDAL.DAL.ConnectionTest(sqlconnnect, ref errormsg);
        }
        /// <summary>
        /// 获取服务器版本信息
        /// </summary>
        /// <param name="loginModel">登陆模式</param>
        /// <param name="databaseModel">数据库实体</param>
        /// <param name="errormsg">错误提示</param>
        /// <returns>版本信息</returns>
        public static string GetDataBaseVerisonInfo(int loginModel, DataBaseInfo databaseModel, ref string errormsg)
        {
            string sqlconnect = DataBaseDAL.DAL.SetConnectionString(loginModel, databaseModel);
            return DataBaseDAL.DAL.GetSqlServerVersionInfo(sqlconnect, ref errormsg);
        }

        /// <summary>
        /// 获取服务器所有数据库信息
        /// </summary>
        /// <param name="loginModel">登陆模式</param>
        /// <param name="databaseModel">数据库实体</param>
        /// <param name="errormsg">错误提示</param>
        /// <returns>服务器所有数据库信息</returns>
        public static List<DataBaseInfo.Database> GetSqlServerDataBaseInfo(int loginModel, DataBaseInfo databaseModel, ref string errormsg)
        {
            string sqlconnect = DataBaseDAL.DAL.SetConnectionString(loginModel, databaseModel);
            return DataBaseDAL.DAL.GetSqlServerDataBaseInfo(sqlconnect, ref errormsg);
        }

        /// <summary>
        /// 获取服务器所有用户信息
        /// </summary>
        /// <param name="loginModel">登陆模式</param>
        /// <param name="databaseModel">数据库实体</param>
        /// <param name="errormsg">错误提示</param>
        /// <returns>服务器的所有用户信息</returns>
        public static List<string> GetSqlServerUserName(int loginModel, DataBaseInfo databaseModel, ref string errormsg)
        {
            string sqlconnect = DataBaseDAL.DAL.SetConnectionString(loginModel, databaseModel);
            return DataBaseDAL.DAL.GetSqlServerUserName(sqlconnect, ref errormsg);
        }

        /// <summary>
        /// 备份数据库
        /// </summary>
        /// <param name="loginModel">登陆模式</param>
        /// <param name="database">数据库实体</param>
        /// <param name="filename">备份路径</param>
        /// <param name="errormsg">错误提示</param>
        /// <returns>true：成功</returns>
        public static bool BackUpDataBase(int loginModel, DataBaseInfo database, string filename, ref string errormsg)
        {
            string sqlconnect = DataBaseDAL.DAL.SetConnectionString(loginModel, database);
            return DataBaseDAL.DAL.BackUpDataBase(sqlconnect, database.InitialCatalog, filename, ref errormsg);

        }
        
        /// <summary>
        /// 恢复数据库
        /// </summary>
        /// <param name="loginModel"></param>
        /// <param name="database"></param>
        /// <param name="filename"></param>
        /// <param name="errormsg"></param>
        /// <returns></returns>
        public static bool RestoreDataBaseByBackUp(int loginModel, DataBaseInfo database, string filename, ref string errormsg)
        {
            string databasename = database.InitialCatalog;
            database.InitialCatalog = "master";
            string sqlconnect = DataBaseDAL.DAL.SetConnectionString(loginModel, database);

            if (DataBaseDAL.DAL.KillDataBaseProcess(sqlconnect, databasename, ref errormsg))
            {
                return DataBaseDAL.DAL.RestoreDataBaseByBackUp(sqlconnect, databasename, filename, ref errormsg);
            }
            else
            {
                return false;

            }
        }

        /// <summary>
        /// 判断数据库是否存在
        /// </summary>
        /// <param name="loginModel"></param>
        /// <param name="database"></param>
        /// <param name="errormsg"></param>
        /// <returns></returns>
        public static bool IsDataBaseExist(int loginModel, DataBaseInfo database, ref string errormsg)
        {
            string databasename = database.InitialCatalog;
            database.InitialCatalog = "master";
            string sqlconnect = DataBaseDAL.DAL.SetConnectionString(loginModel, database);
            bool test = DataBaseDAL.DAL.IsDataBaseExist(sqlconnect, databasename, ref errormsg);
            database.InitialCatalog = databasename;
            return test;
        }

        /// <summary>
        /// 删除数据库
        /// </summary>
        /// <param name="loginModel"></param>
        /// <param name="database"></param>
        /// <param name="errormsg"></param>
        /// <returns></returns>
        public static bool DeleteDataBase(int loginModel, DataBaseInfo database, ref string errormsg)
        {
            string databasename = database.InitialCatalog;
            database.InitialCatalog = "master";
            string sqlconnect = DataBaseDAL.DAL.SetConnectionString(loginModel, database);
            bool test = DataBaseDAL.DAL.DeleteDataBase(sqlconnect, databasename, ref errormsg);
            return test;
        }

        /// <summary>
        /// 用脚本创建数据库
        /// </summary>
        /// <param name="loginModel"></param>
        /// <param name="database"></param>
        /// <param name="scriptname"></param>
        /// <param name="path"></param>
        /// <param name="errormsg"></param>
        /// <returns></returns>
        public static bool CreateDataBaseByScript(int loginModel, DataBaseInfo database, string scriptname, string path, ref string errormsg)
        {
            string databasename = database.InitialCatalog;
            database.InitialCatalog = "master";
            string sqlconnect = DataBaseDAL.DAL.SetConnectionString(loginModel, database);
            if (DataBaseDAL.DAL.CreateEmptyDataBase(sqlconnect, databasename, path, ref errormsg))
            {
                database.InitialCatalog = databasename;
                sqlconnect = DataBaseDAL.DAL.SetConnectionString(loginModel, database);
                return DataBaseDAL.DAL.CreateDataBaseByScript(sqlconnect, databasename, path, scriptname, ref errormsg);
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 增加用户
        /// </summary>
        /// <param name="loginModel">访问模式</param>
        /// <param name="database">数据库实体，其中数据库名位为待添加数据库名</param>
        /// <param name="username">用户名</param>
        /// <param name="pwd">密码</param>
        /// <param name="pwdcheck">是否密码强制</param>
        /// <param name="errormsg">错误提示</param>
        /// <returns></returns>
        public static bool AddDataBaseUser(int loginModel, DataBaseInfo database, string username, string pwd, bool pwdcheck, ref string errormsg)
        {
            string sqlconnect = DataBaseDAL.DAL.SetConnectionString(loginModel, database);
            return DataBaseDAL.DAL.AddDataBaseUser(sqlconnect, username, database.InitialCatalog, pwd, pwdcheck, ref errormsg);

        }

        /// <summary>
        /// 判断是否拥有超级用户权限 
        /// </summary>
        /// <returns></returns>
        public static bool IsAdministrator()
        {
            WindowsIdentity identity = WindowsIdentity.GetCurrent();
            if (null != identity)
            {
                WindowsPrincipal principal = new WindowsPrincipal(identity);
                return principal.IsInRole(WindowsBuiltInRole.Administrator);
            }
            return false;
        }

        /// <summary>
        /// 运行当前程序 
        /// </summary>
        /// <param name="name"></param>
        /// <param name="arguments"></param>
        /// <returns></returns>
        public static Process RunProcess(string name, string arguments)
        {
            string path = Path.GetDirectoryName(name);

            if (String.IsNullOrEmpty(path))
            {
                path = Environment.CurrentDirectory;
            }

            ProcessStartInfo info = new ProcessStartInfo
            {
                UseShellExecute = true,
                WorkingDirectory = path,
                FileName = name,
                Arguments = arguments
            };

            if (!IsAdministrator())
            {
                info.Verb = "runas";
            }

            try
            {
                return Process.Start(info);
            }

            catch (Exception ex)
            {
                Trace.WriteLine(ex);
            }

            return null;
        }
 
        /// <summary>
        ///  Get local sqlserver services(sqlserver sqlexpress)
        /// </summary>
        /// <returns></returns>
        public static void GetSqlServerServiceName(List<ServiceController> serName)
        {
            DAL.GetSqlServerServiceName(ref serName);
        }

        /// <summary>
        ///  获取服务状态
        /// </summary>
        /// <param name="serinfor"></param>
        /// <returns></returns>
        public static string GetServiceState(ServiceControllerEx serinfor)
        {
            return DAL.GetServiceState(serinfor);
        }

        /// <summary>
         /// 读取服务启动类型
         /// </summary>
         /// <param name="serivInfor"></param>
         /// <param name="scEx"></param>
         /// <returns></returns>
        public static ServiceControllerEx GetServiceStartType(string serivInfor, ref ServiceControllerEx scEx)
        {
            switch (serivInfor)
            {
                case "Auto":
                    scEx.StartupType = ServiceStartMode.Automatic.ToString();
                    break;
                case "Manual":
                    scEx.StartupType = ServiceStartMode.Manual.ToString();
                    break;
                case "Disabled":
                    scEx.StartupType = ServiceStartMode.Disabled.ToString();
                    break;
                default:
                    break;
            }
            return scEx;
        }

        /// <summary>
        /// 获取服务当前启动类型
        /// </summary>
        /// <param name="scEx"></param>
        /// <returns></returns>
        public static int GetServiceStartType(ref ServiceControllerEx scEx)
        {
            int key = 0;
            switch (scEx.StartupType)
            {
                case "Auto":
                    key = 1;
                    break;
                case "Manual":
                    key = 2;
                    break;
                case "Disabled":
                    key = 3;
                    break;
                default:
                    break;
            }
            return key;
        }

        /// <summary>
        /// 获取协议状态 
        /// </summary>
        /// <param name="DBversion"></param>
        /// <param name="tcp"></param>
        /// <param name="np"></param>
        public static void  GetRemotConnection(string DBversion,ref int tcp,ref int np)
        {
            RegistryKey hlmk = Registry.LocalMachine;
            RegistryKey key;
            if (DBversion.Contains("2000"))
            {
                key = hlmk.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server", true);
                RegistryKey tcpKey;
                RegistryKey npKey;

                string[] keynames = key.GetSubKeyNames();
                foreach (string keyname in keynames)
                {
                    if (keyname.Contains("MSSQL"))
                    {
                        tcpKey = hlmk.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\" + keyname + @"\MSSQLServer\SuperSocketNetLib\Tcp", true);
                        npKey = hlmk.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\" + keyname + @"\MSSQLServer\SuperSocketNetLib\Np", true);
                        if (tcpKey != null && npKey != null)
                        {
                            tcp = (int)tcpKey.GetValue("Enabled");
                            np = (int)npKey.GetValue("Enabled");
                            break;
                        }
                    }
                }
            }
            else if (DBversion.Contains("2005"))
            {
                //判断数据库版本
                key = hlmk.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server", true);
                RegistryKey tcpKey;
                RegistryKey npKey;

                string[] keynames = key.GetSubKeyNames();
                foreach (string keyname in keynames)
                {
                    if (keyname.Contains("MSSQL.1")) // sql server develop edition
                    {
                        tcpKey = hlmk.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\" + keyname + @"\MSSQLServer\SuperSocketNetLib\Tcp", true);
                        npKey = hlmk.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\" + keyname + @"\MSSQLServer\SuperSocketNetLib\Np", true);
                        if (tcpKey != null && npKey != null)
                        {
                            tcp = (int)tcpKey.GetValue("Enabled");
                            np = (int)npKey.GetValue("Enabled");
                            break;
                        }
                    }
                }
            }
            else  if(DBversion.Contains("2008"))
            {
                key = hlmk.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server", true);
                RegistryKey tcpKey;
                RegistryKey npKey;

                string[] keynames = key.GetSubKeyNames();
                foreach (string keyname in keynames)
                {
             
                    if (keyname.Equals("MSSQL10.SQLEXPRESS")) //sql express 2008
                    {
                        tcpKey =hlmk.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\" + keyname + @"\MSSQLServer\SuperSocketNetLib\Tcp", true);
                        npKey =hlmk.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\" + keyname + @"\MSSQLServer\SuperSocketNetLib\Np", true);
                        if (tcpKey!=null && npKey!=null)
                        {
                            tcp = (int)tcpKey.GetValue("Enabled");
                            np = (int)npKey.GetValue("Enabled");
                            break;
                        }            
                    }
                }
            }
        }

        /// <summary>
        /// 设置当前服务器协议状态 
        /// </summary>
        /// <param name="DBversion"></param>
        /// <param name="tcp"></param>
        /// <param name="np"></param>
        public static void  SetRemotConnection(string DBversion,int tcp,int np)
        {
            RegistryKey hlmk = Registry.LocalMachine;
            RegistryKey key;
            if (DBversion.Contains("2000"))
            {
                key = hlmk.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server", true);
                RegistryKey tcpKey;
                RegistryKey npKey;

                string[] keynames = key.GetSubKeyNames();
                foreach (string keyname in keynames)
                {
                    if (keyname.Contains("MSSQL"))
                    {
                        tcpKey = hlmk.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\" + keyname + @"\MSSQLServer\SuperSocketNetLib\Tcp", true);
                        npKey = hlmk.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\" + keyname + @"\MSSQLServer\SuperSocketNetLib\Np", true);
                        if (tcp == 1)
                        {
                            tcpKey.SetValue("Enabled", 1);
                        }
                        if (np == 1)
                        {
                            npKey.SetValue("Enabled", 1);
                        }
                        break;
                    }
                }
            }
            else if (DBversion.Contains("2005"))
            {
                key = hlmk.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server", true);
                RegistryKey tcpKey;
                RegistryKey npKey;

                string[] keynames = key.GetSubKeyNames();
                foreach (string keyname in keynames)
                {
                    if (keyname.Contains("MSSQL")) // sql develop edition
                    {
                        tcpKey = hlmk.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\" + keyname + @"\MSSQLServer\SuperSocketNetLib\Tcp", true);
                        npKey = hlmk.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\" + keyname + @"\MSSQLServer\SuperSocketNetLib\Np", true);
                        if (tcp == 1)
                        {
                            tcpKey.SetValue("Enabled", 1);
                        }
                        else
                        {
                            tcpKey.SetValue("Enabled", 0);
                        }
                        if (np == 1)
                        {
                            npKey.SetValue("Enabled", 1);
                        }
                        else
                        {
                            npKey.SetValue("Enabled", 0);
                        }
                        break;
                    }

                    if (keyname.Contains("MSSQL.1")) // sql server express
                    {
                        tcpKey = hlmk.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\" + keyname + @"\MSSQLServer\SuperSocketNetLib\Tcp", true);
                        npKey = hlmk.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\" + keyname + @"\MSSQLServer\SuperSocketNetLib\Np", true);
                        if (tcp == 1)
                        {
                            tcpKey.SetValue("Enabled", 1);
                        }
                        else
                        {
                            tcpKey.SetValue("Enabled", 0);
                        }
                        if (np == 1)
                        {
                            npKey.SetValue("Enabled", 1);
                        }
                        else
                        {
                            npKey.SetValue("Enabled", 0);
                        }
                        break;
                    }

                }
            }
            else  if(DBversion.Contains("2008"))
            {
                key = hlmk.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server", true);
                RegistryKey tcpKey;
                RegistryKey npKey;

                string[] keynames = key.GetSubKeyNames();
                foreach (string keyname in keynames)
                {
                    if (keyname.Equals("MSSQL10")) //sql server express 2008
                    {
                        tcpKey = hlmk.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\" + keyname + @"\MSSQLServer\SuperSocketNetLib\Tcp", true);
                        npKey = hlmk.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\" + keyname + @"\MSSQLServer\SuperSocketNetLib\Np", true);
                        if (tcp == 1)
                        {
                            tcpKey.SetValue("Enabled", 1);
                        }
                        else
                        {
                            tcpKey.SetValue("Enabled", 0);
                        }
                        if (np == 1)
                        {
                            npKey.SetValue("Enabled", 1);
                        }
                        else
                        {
                            npKey.SetValue("Enabled", 0);
                        }
                        break;
                    }

                    if (keyname.Equals("MSSQL10.SQLEXPRESS")) //sql server express 2008
                    {
                        tcpKey =hlmk.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\" + keyname + @"\MSSQLServer\SuperSocketNetLib\Tcp", true);
                        npKey =hlmk.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\" + keyname + @"\MSSQLServer\SuperSocketNetLib\Np", true);
                        if (tcp == 1)
                        {
                            tcpKey.SetValue("Enabled", 1);
                        }
                        else
                        {
                            tcpKey.SetValue("Enabled", 0);
                        }
                        if (np == 1)
                        {
                            npKey.SetValue("Enabled", 1);
                        }
                        else
                        {
                            npKey.SetValue("Enabled", 0);
                        }
                        break;
                    }
                }
            }
       }

        /// <summary>
        /// 打开服务 
        /// </summary>
        /// <param name="serName"></param>
        /// <returns></returns>
        public static bool OpenService(string serName)
        {
            DataBaseDAL.ServiceControllerEx scEx = new DataBaseDAL.ServiceControllerEx(serName);
            if (scEx.Status == ServiceControllerStatus.Running)
            {
                return true;
            }
            if (scEx.Status == ServiceControllerStatus.Stopped)
            {
                if (DataBaseDAL.BLL.GetServiceStartType(ref scEx) != 3)
                {
                    try
                    {
                        scEx.Start();
                        scEx.WaitForStatus(ServiceControllerStatus.Running);
                        return true;
                    }
                    catch (Exception ex)
                    {
                        return false;
                    }
                }
            }
            return false;
        }


        public static void  AutoConfigSQLServerDevelop(string DBversion)
        {
           

        }

        public static void AutoConfigSQLServerExpress(string DBversion)
        {


        }
    }
}
